from textual.screen import ModalScreen
from textual.widgets import Button, Input, Static
from textual.containers import Grid
from screens.file_editor import FileEditScreen
import os


class AddFileScreen(ModalScreen[bool]):  # 设置界面
    CSS = """
        Input:focus {
            border: tall orange;
        }
    """
    def __init__(self, fold_path: str, file_type) -> None:  # parent_fold 例如： /root
        super().__init__()
        if fold_path != '/':
            self.fold_path = fold_path+'/'  # self.parent_fold 例如：  /root/
        else:
            self.fold_path = fold_path  # self.parent_fold 例如：  /
        self.file_type = file_type  # 文件夹/文件

    def compose(self):
        yield Grid(
            Static(self.fold_path, id="add_file_title"),
            Input(id="add_file_input"),
            Button("创建", variant="success", id="add_file_confirm"),
            Button("取消", variant="error", id="add_file_quit"),
            id="add_file_window",
        )


    def on_mount(self):
        self.query_one("#add_file_input").focus()
        self.query_one("#add_file_input").cursor_position = 0

    def create_file(self):
        if self.file_type == "file":
            file_name = self.fold_path+self.query_one("#add_file_input").value
            os.system("> "+ file_name)
            self.dismiss(True)
            try:
                self.app.uninstall_screen("FileEditor")
            finally:
                self.app.install_screen(FileEditScreen(file_name=file_name), name="FileEditor")
                async def check_result(result: bool):
                    if result:
                        self.app.update_disk_label()
                self.app.push_screen("FileEditor",check_result)

        elif self.file_type == "fold":
            self.dismiss(True)
            fold_name = self.fold_path+self.query_one("#add_file_input").value
            os.system("mkdir "+ fold_name)
            

    def key_enter(self):
        if self.query_one("#add_file_input").has_focus:
            self.query_one("#add_file_confirm").press()

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "add_file_quit":
            self.dismiss(False)
        else:  # 创建
            self.create_file()
            

